//
// PatchworkView.m
//
// Matt Pharr- pharr@cs.yale.edu
//

#import "PatchworkView.h"
#import <appkit/appkit.h>
#import <dpsclient/wraps.h>
#import <defaults/defaults.h>
#import <libc.h>
#import <stdlib.h>


@implementation PatchworkView

- oneStep
{
    float red, green, blue;

    /* Sure, some boxes will be partially or fully off-screen, but this way, */
    /* the edges of the screen aren't missed most of the time.... */

    theBox.origin.x= randBetween(bounds.origin.x - 50, bounds.size.width + 50);
    theBox.origin.y= randBetween(bounds.origin.y - 50, bounds.size.height + 50);
    theBox.size.width= randBetween(0.0, bounds.size.width - theBox.origin.x + 50);
    theBox.size.height= randBetween(0.0, bounds.size.height - theBox.origin.y + 50);

    if ([Window defaultDepthLimit] == NX_TwoBitGrayDepth) {
        /* Black And White Machines */
        color= randBetween(0.0, 1.0);
        if ((int)(15 * color) == 1) {            /* This way, solidly black squares */
            color= 0.0;                          /* are more common, just to be totally */
        }                                        /* paranoid about avoiding burn-in */
        PSsetgray(color);
    }

    else {                                       /* thanks a bunch to */
        red= randBetween(0.0, 1.0);              /* rob@lighthouse.com for */
        green= randBetween(0.0, 1.0);            /* writing and sending me */
        blue= randBetween(0.0, 1.0);             /* the code to do it in */
        if ((int)(15 * red) == 1) {              /* color on color machines... */
            red= green= blue= 0.0;
        } 
        PSsetrgbcolor(red,green,blue);
    }

    PSrotate(randBetween(0.0, 90.0));
    NXRectFill(&theBox);
	
    usleep((10-speed) * 6000);
 
    return self;
}


- initFrame:(const NXRect *)frameRect
{
    [super initFrame:frameRect];

    [self inspector:self];

    if (NXGetDefaultValue([NXApp appName], "patchViewSpeed") == NULL) {
        NXWriteDefault([NXApp appName], "patchViewSpeed", "5.0");
        speed= 5.0;
    }
    else
        speed= atof(NXGetDefaultValue([NXApp appName], "patchViewSpeed"));

    [theSlider setFloatValue:speed];
    [theSlider update];
	
    return self;
}


- drawSelf:(const NXRect *)rects :(int)rectCount
{
    if (!rects || !rectCount) {
        return self;
    }

    PSsetgray(0.0);
    NXRectFill(rects);

    return self;
}


- (const char *)windowTitle
{
    return "Patchwork";
}


- inspector:sender
{
    char buf[MAXPATHLEN];

    if (!sharedInspectorPanel) {
        sprintf(buf,"%s/%s",[(BSThinker()) moduleDirectory:"Patchwork"],"Patchwork.nib");
        [NXApp loadNibFile:buf owner:self withNames:NO];
    }

    return sharedInspectorPanel;
}


-setSpeed:sender
{
    char temp[20];
	
    speed= [sender floatValue];
	
    sprintf(temp, "%f", speed);
    NXWriteDefault([NXApp appName], "patchViewSpeed", temp);

    return self;
}

@end

